package com.yiwei.hdb.util;

import android.util.Base64;

import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;


/**
 * AES 加密/解密
 * Created by Master.Dong on 2016/4/11.
 */
public class CryptAES{

    private static final String AESTYPE ="AES/ECB/PKCS5Padding";

    public static String AES_Encrypt(String keyStr, String plainText) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        byte[] encrypt = null;
        Key key = generateKey(keyStr);
        Cipher cipher = Cipher.getInstance(AESTYPE);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        encrypt = cipher.doFinal(plainText.getBytes());
        //return URLCoder.encode(new String(org.apache.commons.codec.binary.Base64.encodeBase64(encrypt)));
        return URLCoder.encode(new String(Base64.encode(encrypt, Base64.DEFAULT)));
    }

    public static String AES_Decrypt(String keyStr, String encryptData) throws InvalidKeyException, BadPaddingException, IllegalBlockSizeException, NoSuchPaddingException, NoSuchAlgorithmException {
        byte[] decrypt = null;
        Key key = generateKey(keyStr);
        Cipher cipher = Cipher.getInstance(AESTYPE);
        cipher.init(Cipher.DECRYPT_MODE, key);
        //decrypt = cipher.doFinal(org.apache.commons.codec.binary.Base64.decodeBase64(encryptData));
        decrypt = cipher.doFinal(Base64.decode(encryptData, Base64.DEFAULT));
        return new String(decrypt).trim();
    }

    private static Key generateKey(String key){
            SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "AES");
            return keySpec;
    }

}
